var currentLevel;
var newLevel;
var afters;
var maintainItems = new Array();
var itemList;
var shortcutList;
var selectedIndex = -1;

$(document).ready(function(){
	freshItemShortcuts();
	
	addFadeEffect();
});

function freshItemShortcuts() {
	var requestUrl = "get_item_shortcut";
	
	var params = {
		page:1,
		page_size:999
	};
	
	$.post(requestUrl, params, function(ret){
		$("#div_shortcuts").html("");
		var newHtml = "";
		var item;
		
		shortcutList = ret.resultData.items;
				
		//显示结果列表
		for (var i = 0; ret.resultData.items && i < ret.resultData.items.length; i++) {
			item = ret.resultData.items[i];
			
			newHtml += '<div align="center" style="width: 155px; height: 160px; float: left;">';
			newHtml += '	<div style="width: 125px; cursor: pointer;" onclick="saveNewItemByShortcut(\'' + i + '\')">';
			newHtml += '		<img src="' + WSContextPath + "/" + item.itemPhoto + '" width="124px" height="124px">';
			newHtml += '		<div style="line-height: 30px;">' + item.shortcutName + '</div>';
			newHtml += '	</div>';
			newHtml += '</div>';
		}
		
		newHtml += '<div style="clear: both;"></div>';
		
		$("#div_shortcuts").html(newHtml);
	}, dataType="json");
}

function freshItemList() {
	var newHtml = "";
	var item;
	
	//显示结果列表
	for (var i = 0; i < maintainItems.length; i++) {
		item = maintainItems[i];
		if (item == null) {continue;}
		
		newHtml += '<div style="padding-top: 2px">';
		newHtml += '    <div class="col_maintain_item">' + item.item_type + '</div>';
		newHtml += '    <div class="col_item_brand">' + item.item_brand + '</div>';
		newHtml += '	<div class="col_item_type">' + item.item_model + '</div>';
		newHtml += '    <div class="col_item_cycle">' + item.item_period + '</div>';
		newHtml += '    <div class="maintain_item_control" align="left" style="float: left; padding-top: 3px;">';
		newHtml += '        <img class="pointer fade_effect" src="' + contextPath + '/image/btn_modify.png" style="margin-left: 15px;"/>';
		newHtml += '        <img class="pointer fade_effect" src="' + contextPath + '/image/btn_delete.png" onclick="deleteItem(\'' + i + '\');"/>';
		newHtml += '    </div>';
		newHtml += '	<div style="clear: both;"></div>';
		newHtml += '</div>';
	}
	
	$("#div_maintain_item_list").html(newHtml);
	addFadeEffect();
}

function deleteItem(index) {
	maintainItems[index] = null;
	
	freshItemList();
}

function saveNewItem() {
	//未选中项目时
	if (selectedIndex < 0) {return;}
	
	//保存选择项
	maintainItems[maintainItems.length] = {
			item_id:itemList[selectedIndex].itemId,
			item_brand:itemList[selectedIndex].itemBrandName,
			item_type:itemList[selectedIndex].itemTypeName,
			item_period:itemList[selectedIndex].itemPeriodName,
			item_model:itemList[selectedIndex].itemModel};
	
	//刷新项目列表
	freshItemList();
}

function saveNewItemByShortcut(index) {	
	//保存选择项
	maintainItems[maintainItems.length] = {
			item_id:shortcutList[index].itemId,
			item_brand:shortcutList[index].itemBrand,
			item_type:shortcutList[index].itemType,
			item_period:shortcutList[index].itemPeriod,
			item_model:shortcutList[index].itemModel};
	
	//刷新项目列表
	freshItemList();
}

function changeLevel(selected, hasChild) {
	selectedIndex = -1;
	currentLevel = $(selected).parent().parent().parent().children().length;
	newLevel = eval($(selected).parent().parent().attr("class")) + 1;
	afters = "";
	
	for(var i = newLevel; i < currentLevel; i++) {
		afters += ",." + i;
	}
	$(afters).remove();
	
	if (hasChild) {
		$("#div_scroll").css("width", (202 * newLevel) + "px");
		moveRight();
	}
	
	$(selected).parent().parent().find(".option").css("background", "");
	$(selected).css("background", "#316ac5");
}

function moveLeft() {
	$("#div_scroll_bar").scrollLeft($("#div_scroll_bar").scrollLeft() - 202);
}

function moveRight() {
	$("#div_scroll_bar").scrollLeft($("#div_scroll_bar").scrollLeft() + 202);
}

function selectOption(selected, typeId) {
	changeLevel(selected, true);
	
	var requestUrl = contextPath + "/get_item_type";
	var params = {
		parent_id:typeId
	};
	$.post(requestUrl, params, function(data){
		var nextLevelHtml = "";
		
		nextLevelHtml += '<div class="' + newLevel + '" style="float: left; width: 200px; height: 160px; overflow-y: scroll; background: white; border: inset 1px gray;">';
		for (var i = 0; data.resultData && i < data.resultData.length; i++) {
			var type = data.resultData[i];
			var clickEvent = type.isLeaf ? "selectType" : "selectOption";
			nextLevelHtml += '	<div style="background: url(../image/right_arrow.png) right no-repeat;">';
			nextLevelHtml += '		<div class="option" style="padding-right: 20px;" onclick="' + clickEvent + '(this, \'' + type.typeId + '\');">' + type.typeName + '</div>';
			nextLevelHtml += '	</div>';
		}
		nextLevelHtml += '</div>';
		
		$(selected).parent().parent().after(nextLevelHtml);
	}, "json");
}

function selectType(selected, typeId) {
	changeLevel(selected, true);
	
	$(selected).parent().parent().find(".option").css("background", "");
	$(selected).css("background", "#316ac5");
	
	var requestUrl = contextPath + "/get_item_brand";
	var params = {
		type_id:typeId
	};
	$.post(requestUrl, params, function(data){
		var nextLevelHtml = "";
		
		nextLevelHtml += '<div class="' + newLevel + '" style="float: left; width: 200px; height: 160px; overflow-y: scroll; background: white; border: inset 1px gray;">';
		for (var i = 0; data.resultData && i < data.resultData.length; i++) {
			var brand = data.resultData[i];
			nextLevelHtml += '	<div style="background: url(../image/right_arrow.png) right no-repeat;">';
			nextLevelHtml += '		<div class="option" onclick="selectBrand(this, \'' + typeId + '\', \'' + brand.brandId + '\');">' + brand.brandName + '</div>';
			nextLevelHtml += '	</div>';
		}
		nextLevelHtml += '</div>';
		
		$(selected).parent().parent().after(nextLevelHtml);
	}, "json");
}

function selectBrand(selected, typeId, brandId) {
	changeLevel(selected, true);
	
	var requestUrl = contextPath + "/get_maintain_item";
	var params = {
		type_id:typeId,
		brand_id:brandId
	};
	$.post(requestUrl, params, function(data){
		var nextLevelHtml = "";
		itemList = data.resultData;
		
		nextLevelHtml += '<div class="' + newLevel + '" style="float: left; width: 200px; height: 160px; overflow-y: scroll; background: white; border: inset 1px gray;">';
		for (var i = 0; data.resultData && i < data.resultData.length; i++) {
			var item = data.resultData[i];
			nextLevelHtml += '	<div>';
			nextLevelHtml += '		<div class="option" onclick="selectItem(this, \'' + i + '\');">' + item.itemModel + '</div>';
			nextLevelHtml += '	</div>';
		}
		nextLevelHtml += '</div>';
		
		$(selected).parent().parent().after(nextLevelHtml);
	}, "json");
}

function selectItem(selected, index) {
	changeLevel(selected, false);
	
	selectedIndex = index;
}

function toggleAddItemDiv() {
	if ($('#div_add_new_item').css('display') == "none") {
		$('#div_add_new_item').css('display', '');
	} else {
		$('#div_add_new_item').css('display', 'none');
	}
}

//输入状态确认
var errorMileage = true;
var errorPlaceId = true;
var errorTotalFee = true;

function checkMileage() {
	var pattern = /^[0-9]{1,11}$/;
	var mileage = $("#mileage").val();
	
	if (mileage == "" || !pattern.test(mileage)) {
		$("#error_message").html("保养里程错误<br/>");
		$("#mileage").css("background", "#fbe2e2");
		errorMileage = true;
	} else {
		$("#error_message").html("");
		$("#mileage").css("background", "#ffffff");
		errorMileage = false;
	}
	return true;
}

function checkPlaceId() {
	var placeId = $("#place_id").val();
	
	if (placeId == "") {
		$("#error_message").html("请选择维修店<br/>");
		$("#place_id").css("background", "#fbe2e2");
		errorPlaceId = true;
	} else {
		$("#error_message").html("");
		$("#place_id").css("background", "#ffffff");
		errorPlaceId = false;
	}
	return true;
}

function checkTotalFee() {
	var pattern = /^[0-9]{1,10}(\.[0-9]{1,2})?$/;
	var totalFee = $("#total_fee").val();
	
	if (totalFee == "" || !pattern.test(totalFee)) {
		$("#error_message").html("养护费用错误<br/>");
		$("#total_fee").css("background", "#fbe2e2");
		errorTotalFee = true;
	} else {
		$("#error_message").html("");
		$("#total_fee").css("background", "#ffffff");
		errorTotalFee = false;
	}
	return true;
}

function addMaintainOrder() {
	if (checkMileage() && !errorMileage
			&& checkPlaceId() && !errorPlaceId
			&& checkTotalFee() && !errorTotalFee) {
		var requestUrl = "add_maintain_order";
		var carLicense = "";
		var customerName = "";
		var customerMobile = "";
		var items = new Array();
		
		for(var i = 0; i < maintainItems.length; i++) {
			if (maintainItems[i] == null) {continue;}
			items[items.length] = maintainItems[i];
		}
		
		if (customers != null && selectedCusutomerIndex) {
			carLicense = customers[selectedCusutomerIndex].carLicense;
			customerName = customers[selectedCusutomerIndex].name;
			customerMobile = customers[selectedCusutomerIndex].mobile;
			
			var params = {
					car_license:carLicense,
					name:customerName,
					mobile:customerMobile,
					mileage:$("#mileage").val(),
					maintain_date:$("#maintain_date").val(),
					maintain_place:$("#place_id").val(),
					maintain_fee:$("#total_fee").val(),
					comment:$("#comment").val(),
					maintain_items:JSON.stringify(items)
				};
				
			$.post(requestUrl, params, function(data){
				showMaintainList();
			});
		} else {
			var params = {license_number:selectedMaintainOrderLicense};
			
			//根据当前记录的车牌查询客户信息
			$.post(contextPath + "/merchant/search_customer", params, function(data){
				try {
					var item = data.resultData.items[0];
					
					carLicense = selectedMaintainOrderLicense;
					customerName = item.name;
					customerMobile = item.mobile;
					
					var params = {
							car_license:carLicense,
							name:customerName,
							mobile:customerMobile,
							mileage:$("#mileage").val(),
							maintain_date:$("#maintain_date").val(),
							maintain_place:$("#place_id").val(),
							maintain_fee:$("#total_fee").val(),
							comment:$("#comment").val(),
							maintain_items:JSON.stringify(items)
						};
						
					$.post(requestUrl, params, function(data){
						showMaintainList();
					});
				} catch (e) {
				}
			}, "json");
		}
	}
}